from app import app
from flask import Flask, request, jsonify, make_response, session
from app.libs.API_used import API_query_addr
from app.libs.Verifys import passWord, verifyPhone
from app.models import *
from app.libs.Codes import ImgCode, SmsCode
from app.libs.Crypto_used import AesCrypto, Md5Crypto
from app.admin.admin_login import admin_require
from app.libs.QINIU import delect as QiniuDel, pfop_m3u8
from sqlalchemy import or_
from app.setting import AESKEY, MD5KEY
import uuid
from app.user.user_login import user_require
from flask_restful import inputs

import time
import hashlib
import random
from app.setting import *
from urllib import parse
import base64
import json


# 访客进入
@app.route('/pdd/visitor', methods=["post"])
def visitor():
    sign = request.cookies.get('v_sign')
    addr = request.headers.get("X-Real-IP", default="127.0.0.1")
    landing = request.form.get('landing', type=str)
    source = request.form.get("referrer", type=str)

    if source:
        url = parse.urlparse(source)
        sites = url.netloc

        if 'baidu' in sites:
            keyword = parse.parse_qs(url.query).get("wd")[0]
            sources = '百度搜索'

        elif 'sogou' in sites:
            keyword = parse.parse_qs(url.query).get("query")[-1]
            sources = '搜狗搜索'

        elif 'so.' in sites:
            keyword = parse.parse_qs(url.query).get("q")[-1]
            sources = '360搜索'

        else:
            keyword = '其他访客'
            sources = '其他访客'

    else:
        keyword = '直接进入'
        sources = '直接进入'
        sites = "直接进入"

    if sign:
        ret = Visitor.query.filter(Visitor.sign == sign).first()
        if ret:
            ret.leave = landing
            db.session.commit()
            resp = {'code': 0, 'msg': 'ok'}
            return resp
        else:
            localAddress = API_query_addr(addr)
            sign = str(time.time()) + str(random.randint(999, 9999)) + "&pdlllasSADFFF"
            m = hashlib.md5()
            sign = sign.encode(encoding='utf-8')
            m.update(sign)
            sign = m.hexdigest()
            vobj = Visitor(sign=sign, addr=addr, source=sources, keyword=keyword, referer=sites, landing=landing,
                           leave=landing,
                           islogin=False, city=localAddress.get("city"), province=localAddress.get("province"))
            try:
                db.session.add(vobj)
                db.session.commit()
                resp = make_response(jsonify({'code': 0, 'msg': 'ok'}))
                expires = datetime.datetime.now() + datetime.timedelta(days=30, hours=16)
                resp.set_cookie('v_sign', vobj.sign, expires=expires)
                return resp
            except:
                db.session.rollback()
                resp = make_response(jsonify({'code': -1, 'msg': 'no'}))

                return resp

    else:

        sign = str(time.time()) + str(random.randint(999, 9999)) + "&pdlllasSADFFF"
        m = hashlib.md5()
        sign = sign.encode(encoding='utf-8')
        m.update(sign)
        sign = m.hexdigest()
        localAddress = API_query_addr(addr)
        vobj = Visitor(sign=sign, addr=addr, source=sources, keyword=keyword, referer=sites, landing=landing,
                       leave=landing,
                       islogin=False, city=localAddress.get("city"), province=localAddress.get("province"))
        try:
            db.session.add(vobj)
            db.session.commit()
            resp = make_response(jsonify({'code': 0, 'msg': 'succeed'}))
            expires = datetime.datetime.now() + datetime.timedelta(days=365, hours=16)
            resp.set_cookie('v_sign', vobj.sign, expires=expires)
            return resp
        except:
            db.session.rollback()
            resp = make_response(jsonify({'code': -1, 'msg': 'fail'}))

            return resp


# 注册
@app.route('/pdd/register', methods=["post"])
def register():
    sign = request.cookies.get('v_sign')
    keyword = ""
    source = "直接进入"
    if sign:
        v = Visitor.query.filter(Visitor.sign == sign).first()
        if v:
            keyword = v.keyword
            source = v.source
        else:
            keyword = ""
            source = "直接进入"

    phone = request.form.get("phone", type=str)
    password = request.form.get("password", type=str)
    code = request.form.get("code", type=str)

    if phone is None:
        return jsonify(code=-1, msg="请输入正确的手机号")

    if not verifyPhone.match(phone):
        return jsonify(code=-1, msg="请输入正确的手机号")

    if password is None:
        return jsonify(code=-1, msg="请输入密码")

    if code is None:
        return jsonify(code=-1, msg="请输入验证码")

    r_sms = session.get("r_sms")
    if r_sms is None:
        return jsonify(code=-1, msg="手机号验证码错误")

    try:
        r_sms_phone = r_sms.get("phone")
        r_sms_code = r_sms.get("code")
        r_sms_time = r_sms.get("time")
        if phone != r_sms_phone:
            return jsonify(code=-1, msg="手机号验证码错误")
        if r_sms_code != code:
            return jsonify(code=-1, msg="手机号验证码错误")

        if r_sms_time + 60 * 2 < int(time.time()):
            return jsonify(code=-1, msg="验证码失效")

    except:
        return jsonify(code=-1, msg="手机号验证码错误")

    ret = passWord(password=password, lenMax=25, lenMin=8)
    if ret == 2:
        return jsonify(code=-1, msg="密码长度不能低于8位")
    if ret == 3:
        return jsonify(code=-1, msg="密码长度不能高于25位")
    if ret == 4:
        return jsonify(code=-1, msg="输入的密码为数字字母加字符的任意组合")
    user = User.query.filter(User.phone == phone).first()
    if user:
        return jsonify(code=-1, msg="手机号已被注册")

    username = recursion_usr()
    sell = UserSell(keyword=keyword, wechat=None, source=source)
    sell.user = [User(username=username, phone=phone, integral=300, password=password)]
    try:
        db.session.add(sell)
        db.session.commit()
        return jsonify(code=0, msg="注册成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="注册失败")


# 短信登录
@app.route('/pdd/sms/login', methods=["post"])
def sms_login():
    phone = request.form.get("phone", type=str)
    code = request.form.get("code", type=str)

    if phone is None:
        return jsonify(code=-1, msg="请输入正确的手机号")

    if not verifyPhone.match(phone):
        return jsonify(code=-1, msg="请输入正确的手机号")

    if code is None:
        return jsonify(code=-1, msg="请输入验证码")

    r_sms = session.get("r_sms")
    if r_sms is None:
        return jsonify(code=-1, msg="手机号验证码错误")

    try:
        r_sms_phone = r_sms.get("phone")
        r_sms_code = r_sms.get("code")
        r_sms_time = r_sms.get("time")
        if phone != r_sms_phone:
            return jsonify(code=-1, msg="手机号验证码错误")
        if r_sms_code != code:
            return jsonify(code=-1, msg="手机号验证码错误")

        if r_sms_time + 60 * 2 < int(time.time()):
            return jsonify(code=-1, msg="验证码失效")

    except:
        return jsonify(code=-1, msg="手机号验证码错误")

    user = User.query.filter(User.phone == phone).first()
    if user:
        cookie = recursion_cookies()
        cobj = User_Cookies(cookies=cookie,
                            endTime=(datetime.datetime.now() + app.config['PEMEMBER_COOKIE_DURATION']).timetuple(),
                            uid=user.id)
        try:
            db.session.add(cobj)
            db.session.commit()

            resp = make_response(jsonify(code=0, msg="登录成功"))
            resp.set_cookie('uid', cookie)
            return resp
        except:
            db.session.rollback()
            resp = make_response(jsonify(code=-1, msg="登录失败"))
            resp.delete_cookie("uid")
            return resp
    else:

        sign = request.cookies.get('v_sign')
        keyword = ""
        source = "直接进入"
        if sign:
            v = Visitor.query.filter(Visitor.sign == sign).first()
            if v:
                keyword = v.keyword
                source = v.source
            else:
                keyword = ""
                source = "直接进入"

        username = recursion_usr()
        sell = UserSell(keyword=keyword, wechat=None, source=source)
        user = User(username=username, phone=phone, integral=300, password=None)
        sell.user = [user]
        cookie = recursion_cookies()
        cobj = User_Cookies(cookies=cookie,
                            endTime=(datetime.datetime.now() + app.config['PEMEMBER_COOKIE_DURATION']).timetuple(),
                            uid=user.id)
        try:
            db.session.add(sell)
            db.session.add(cobj)
            db.session.commit()
            resp = make_response(jsonify(code=0, msg="登录成功"))
            resp.set_cookie('uid', cookie)
            return resp

        except:
            db.session.rollback()
            resp = make_response(jsonify(code=-1, msg="登录失败"))
            resp.delete_cookie("uid")
            return resp


# 登录
@app.route('/pdd/login', methods=["post"])
def login():
    addr = request.headers.get("X-Real-IP", default="127.0.0.1")
    phone = request.form.get("phone", type=str)
    password = request.form.get("password", type=str)
    utoken = request.headers.get("utoken", type=str)

    if utoken is None:
        return jsonify(code=-1, msg="请通过安全验证")

    safe_code = session.get("safe_code")
    if safe_code is None:
        return jsonify(code=-1, msg="请通过安全验证")

    try:
        safe_token = safe_code.get("token")
        safe_time = safe_code.get("times")
        if safe_token != utoken:
            return jsonify(code=-1, msg="请通过安全验证")
        if safe_time + 60 * 3 < int(time.time()):
            return jsonify(code=-1, msg="安全验证失效～")


    except:
        return jsonify(code=-1, msg="请通过安全验证")

    if phone is None:
        return jsonify(code=-1, msg="请输入正确的手机号")

    if not verifyPhone.match(phone):
        return jsonify(code=-1, msg="请输入正确的手机号")

    user = User.query.filter(User.phone == phone).first()
    if not user:
        return jsonify(code=-1, msg="手机号没有注册～")

    if password != user.password:
        return jsonify(code=-1, msg="密码错误～")

    localAddress = API_query_addr(addr)

    login_log = User_login_log(addr=addr, city=localAddress.get("city"), province=localAddress.get("province"),
                               uid=user.id)
    try:
        db.session.add(login_log)
        db.session.commit()
    except:
        db.session.rollback()

    cookie = recursion_cookies()
    cobj = User_Cookies(cookies=cookie,
                        endTime=(datetime.datetime.now() + app.config['PEMEMBER_COOKIE_DURATION']).timetuple(),
                        uid=user.id)
    try:
        db.session.add(cobj)
        db.session.commit()
        resp = make_response(jsonify(code=0, msg="登录成功"))
        resp.set_cookie('uid', cookie)
        return resp
    except:
        db.session.rollback()
        resp = make_response(jsonify(code=-1, msg="登录失败"))
        resp.delete_cookie("uid")
        return resp


# 修改密码
@app.route('/pdd/update/password', methods=["post"])
def update_password():
    phone = request.form.get("phone", type=str)
    password = request.form.get("password", type=str)
    code = request.form.get("code", type=str)
    if phone is None:
        return jsonify(code=-1, msg="请输入正确的手机号")

    if not verifyPhone.match(phone):
        return jsonify(code=-1, msg="请输入正确的手机号")

    if code is None:
        return jsonify(code=-1, msg="请输入验证码")

    r_sms = session.get("r_sms")
    if r_sms is None:
        return jsonify(code=-1, msg="手机号验证码错误")

    try:
        r_sms_phone = r_sms.get("phone")
        r_sms_code = r_sms.get("code")
        r_sms_time = r_sms.get("time")
        if phone != r_sms_phone:
            return jsonify(code=-1, msg="手机号验证码错误")
        if r_sms_code != code:
            return jsonify(code=-1, msg="手机号验证码错误")

        if r_sms_time + 60 * 2 < int(time.time()):
            return jsonify(code=-1, msg="验证码失效")

    except:
        return jsonify(code=-1, msg="手机号验证码错误")

    ret = passWord(password=password, lenMax=25, lenMin=8)
    if ret == 2:
        return jsonify(code=-1, msg="密码长度不能低于8位")
    if ret == 3:
        return jsonify(code=-1, msg="密码长度不能高于25位")
    if ret == 4:
        return jsonify(code=-1, msg="输入的密码为数字字母加字符的任意组合")
    user = User.query.filter(User.phone == phone).first()
    if not user:
        return jsonify(code=-1, msg="用户不存在，请认真检查手机号")

    try:
        user.password = password
        db.session.commit()
        return jsonify(code=0, msg="密码修改成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="密码修改失败")


# 获取头部个人信息
@app.route('/pdd/header/userinfo', methods=["get"])
@user_require
def header_userinfo(uid):
    level = uid.levels.join(UserRank).filter(UserLevel.endTime >= datetime.datetime.now().date()).order_by(
        UserRank.level.desc()).first()
    if not level:
        rank = UserRank.query.filter(UserRank.initial).first()
        level = {
            "name": rank.name,
            "endTime": None,
            "isvip":False,
        }

    else:
        rank = level.rank
        level = {
            "name": rank.name,
            "endTime":str(level.endTime),
            "isvip":True
        }
    data = {
        "nick": uid.nick if uid.nick else uid.username,
        "photo": uid.userPhoto,
        "integral": uid.integral,
        "level": level
    }
    return jsonify(code=0,msg="获取成功",data=data)





# 获取个人中心
@app.route('/pdd/userinfo', methods=["get"])
@user_require
def userinfo(uid):
    level = uid.levels.join(UserRank).filter(UserLevel.endTime >= datetime.datetime.now().date()).order_by(
        UserRank.level.desc()).first()
    if not level:
        rank = UserRank.query.filter(UserRank.initial).first()
        level = {
            "name": rank.name,
            "endTime": None,
            "color":rank.color,
            "background":rank.background,
            "isvip":False,
        }

    else:
        rank = level.rank
        level = {
            "name": rank.name,
            "endTime":str(level.endTime),
            "color": rank.color,
            "background": rank.background,
            "isvip":True
        }

    #常用功能待接入
    usefunclist = []
    #这里接入常用
    limit = 0
    sql = list()
    if len(usefunclist) < 4:
        limit = 4 - len(usefunclist)

    if len(usefunclist)>0:
        sql.append(FuncData.id.notin_([i.id for i in usefunclist]))

    usefunc = FuncData.query.filter(*sql).order_by(FuncData.rank.desc()).limit(limit).all()

    for i in usefunc:
        usefunclist.append({
            "id":i.id,
            "useCount":i.useCount,#待加入统计
            "imgName":i.imgName,
            "href":i.href,
            "name":i.name,
            "intro":i.intro
        })

    recfunc = FuncData.query.order_by(FuncData.rank.desc()).limit(4).all()
    recfunclist = [{
        "id": i.id,
        "useCount": i.useCount,  # 待加入统计
        "imgName": i.imgName,
        "href": i.href,
        "name": i.name,
        "intro": i.intro
    }for i in recfunc]


    data = {
        "nick": uid.nick if uid.nick else uid.username,
        "username":uid.username,
        "photo": uid.userPhoto,
        "phone":uid.phone[:3] + "****" + uid.phone[-3:],
        "integral": uid.integral,
        "level": level,
        "usefunclist":usefunclist,
        "recfunclist":recfunclist,
    }
    return jsonify(code=0,msg="获取成功",data=data)

# 设置用户头像
@app.route('/pdd/user/update/photo', methods=["post"])
@user_require
def update_photo(uid):
    imgName = request.form.get("imgName",type=str)

    if imgName is None:
        return jsonify(code=-1,msg="图片获取失败")

    if uid.userPhoto:
        QiniuDel(uid.userPhoto)
    try:
        uid.userPhoto = imgName
        db.session.commit()
        return jsonify(code=0, msg="头像更改成功")
    except:
        return jsonify(code=-1, msg="头像更改失败")


# 更新用户信息
@app.route('/pdd/user/update/info', methods=["post"])
@user_require
def update_info(uid):
    sex = request.form.get("sex",type=inputs.boolean)
    nick = request.form.get("nick",type=str)


    if sex is None:
        return jsonify(code=-1,msg="请设置性别")

    if nick is None:
        return jsonify(code=-1, msg="请设置昵称")


    try:
        uid.nick = nick
        uid.sex = sex
        db.session.commit()
        return jsonify(code=0, msg="修改成功")
    except:
        db.session.rollback()
        return jsonify(code=0, msg="修改失败")


# 用户退出
@app.route('/pdd/exit', methods=["post"])
def user_exit():
    uid = request.cookies.get("uid")
    if not uid:
        resp = make_response(jsonify({
            'code': -101,
            'msg': '请登录！'
        }))

        resp.delete_cookie("uid")
        return resp

    cookie = User_Cookies.query.filter_by(cookies=uid).first()
    if not cookie:
        resp = make_response(jsonify({
            'code': -101,
            'msg': '请登录！'
        }))
        resp.delete_cookie("uid")
        return resp
    if datetime.datetime.now() < cookie.endTime:
        try:
            db.session.delete(cookie)
            resp = make_response(jsonify({
                'code': 0,
                'msg': '退出成功！'
            }))
            resp.delete_cookie("uid")
            return resp
        except:
            db.session.rollback()
            resp = make_response(jsonify({
                'code': -101,
                'msg': '请登录！'
            }))
            resp.delete_cookie("uid")
            return resp

    else:
        resp = make_response(jsonify({
            'code': -101,
            'msg': '请登录！'
        }))

        resp.delete_cookie("uid")

        return resp









# 获取图片验证码
@app.route('/pdd/user/imgcode', methods=["get", "post"])
def userCode():
    if request.method == "GET":

        imgobj = ImgCode()
        imgData = imgobj.create()
        if imgobj:
            getCodeInfo(imgData.get("session"))
            session["usr_imgcode"] = {"code": imgData.get("session"), "time": int(time.time())}
            text = [i.get("text") for i in imgData.get("session")]

            return jsonify(code=0, msg="获取成功", data={"image": imgData.get("data"), "text": text})


        else:
            return jsonify(code=-1, msg="验证码获取失败")

    if request.method == "POST":
        token = request.headers.get("token", type=str)
        if token is None:
            return jsonify(code=-1, msg="验证码错误")
        session_code = session.get("usr_imgcode")
        if session_code is None:
            return jsonify(code=-1, msg="验证码错误")
        try:
            code_data = session_code.get("code")
            code_time = session_code.get("time")
            aes = AesCrypto(AESKEY)
            decrypted = aes.decrypt(token)
            token = json.loads(base64.b64decode(decrypted))
            if len(token) != 4 or len(code_data) != 4:
                return jsonify(code=-1, msg="验证码错误")
            if code_time + 60 * 2 < int(time.time()):
                return jsonify(code=-2, msg="验证码验证失效")
            for s, k in zip(code_data, token):
                if s.get("x1") <= k.get("x") > s.get("x2"):
                    return jsonify(code=-1, msg="验证码验证失败")
                if s.get("y1") <= k.get("y") > s.get("y2"):
                    return jsonify(code=-1, msg="验证码验证失败")

            token = str(uuid.uuid4())
            session["safe_code"] = {"token": token, "times": int(time.time())}
            return jsonify(code=0, msg="安全验证成功", utoken=token)

        except:
            return jsonify(code=-1, msg="验证码错误")


# 获取手机验证码
@app.route('/pdd/user/smscode', methods=["post"])
def smsCode():
    phone = request.form.get("phone", type=str)
    token = request.headers.get("token", type=str)
    if phone is None:
        return jsonify(code=-1, msg="请输入手机号")

    if not verifyPhone.match(phone):
        return jsonify(code=-1, msg="请输入正确的手机号")

    if token is None:
        return jsonify(code=-1, msg="验证码错误")

    session_code = session.get("usr_imgcode")
    if session_code is None:
        return jsonify(code=-1, msg="验证码错误")
    try:
        code_data = session_code.get("code")
        code_time = session_code.get("time")
        aes = AesCrypto(AESKEY)
        decrypted = aes.decrypt(token)
        token = json.loads(base64.b64decode(decrypted))
        if len(token) != 4 or len(code_data) != 4:
            return jsonify(code=-1, msg="验证码错误")
        if code_time + 60 * 2 < int(time.time()):
            return jsonify(code=-2, msg="验证码验证失效")
        for s, k in zip(code_data, token):
            if s.get("x1") <= k.get("x") > s.get("x2"):
                return jsonify(code=-1, msg="验证码验证失败")
            if s.get("y1") <= k.get("y") > s.get("y2"):
                return jsonify(code=-1, msg="验证码验证失败")

        sms = SmsCode(phone)
        if sms:
            session["r_sms"] = sms
        else:
            return jsonify(code=-1, msg="验证码发送失败")

        return jsonify(code=0, msg="发送成功，有效时间60秒")

    except:
        return jsonify(code=-1, msg="验证码错误")


# 获取准备换绑手机号验证码
@app.route('/pdd/user/update/phone/smscode', methods=["get"])
@user_require
def update_phone_smsCode(uid):
    token = request.headers.get("token", type=str)
    if token is None:
        return jsonify(code=-1, msg="验证码错误")

    session_code = session.get("usr_imgcode")
    if session_code is None:
        return jsonify(code=-1, msg="验证码错误")
    try:
        code_data = session_code.get("code")
        code_time = session_code.get("time")

        aes = AesCrypto(AESKEY)
        decrypted = aes.decrypt(token)
        token = json.loads(base64.b64decode(decrypted))

        if len(token) != 4 or len(code_data) != 4:
            return jsonify(code=-1, msg="验证码错误")

        if code_time + 60 * 2 < int(time.time()):
            return jsonify(code=-2, msg="验证码验证失效")

        for s, k in zip(code_data, token):

            if s.get("x1") <= k.get("x") > s.get("x2"):
                return jsonify(code=-1, msg="验证码验证失败")

            if s.get("y1") <= k.get("y") > s.get("y2"):
                return jsonify(code=-1, msg="验证码验证失败")

        sms = SmsCode(uid.phone)
        if sms:
            session["update_phone_sms"] = sms
        else:
            return jsonify(code=-1, msg="验证码发送失败")

        return jsonify(code=0, msg="发送成功，有效时间180秒")

    except:
        return jsonify(code=-1, msg="验证码错误")


# 获取准备换绑手机号token
@app.route('/pdd/user/update/phone/token', methods=["post"])
@user_require
def update_phone_token(uid):
    code = request.form.get("code",type=str)
    update_sms = session.get("update_phone_sms")
    if update_sms is None:
        return jsonify(code=-1, msg="手机号验证码错误")

    try:
        update_sms_phone = update_sms.get("phone")
        update_sms_code = update_sms.get("code")
        update_sms_time = update_sms.get("time")
        if uid.phone != update_sms_phone:
            return jsonify(code=-1, msg="手机号验证码错误")
        if update_sms_code != code:
            return jsonify(code=-1, msg="手机号验证码错误")

        if update_sms_time + 60 * 2 < int(time.time()):
            return jsonify(code=-1, msg="验证码失效")
        token = str(uuid.uuid4())
        md5 =Md5Crypto(MD5KEY)
        sign = md5.encrypt(token)
        session["update_phone_token"] = {
            "phone":uid.phone,
            "token":token,
            "sign":sign,
            "time":int(time.time())
        }
        return jsonify(code=0,msg="验证成功")

    except:
        return jsonify(code=-1, msg="手机号验证码错误")


# 换绑手机
@app.route('/pdd/user/update/phone', methods=["post"])
@user_require
def update_phone(uid):
    phone = request.form.get("phone",type=str)
    code = request.form.get("code", type=str)

    if phone is None:
        return jsonify(code=-1, msg="请输入手机号")

    if not verifyPhone.match(phone):
        return jsonify(code=-1, msg="请输入正确的手机号")

    if code is None:
        return jsonify(code=-1, msg="请输入验证码")

    r_sms = session.get("r_sms")
    if r_sms is None:
        return jsonify(code=-1, msg="手机号验证码错误")

    try:
        r_sms_phone = r_sms.get("phone")
        r_sms_code = r_sms.get("code")
        r_sms_time = r_sms.get("time")
        if phone != r_sms_phone:
            return jsonify(code=-1, msg="手机号验证码错误")
        if r_sms_code != code:
            return jsonify(code=-1, msg="手机号验证码错误")

        if r_sms_time + 60 * 2 < int(time.time()):
            return jsonify(code=-1, msg="验证码失效")

    except:
        return jsonify(code=-1, msg="手机号验证码错误")

    update_session = session.get("update_phone_token")
    if update_session is None:
        return jsonify(code=-103, msg="请先验证旧手机号")

    try:
        update_phone = update_session.get("phone")
        update_token = update_session.get("token")
        update_sign = update_session.get("sign")
        update_time = update_session.get("time")

        if uid.phone != update_phone:

            return jsonify(code=-103, msg="请先验证旧手机号")
        md5 = Md5Crypto(MD5KEY)
        sign = md5.encrypt(update_token)

        if update_sign != sign:

            return jsonify(code=-103, msg="请先验证旧手机号")

        if update_time + 60 * 5 < int(time.time()):

            return jsonify(code=-103, msg="请先验证旧手机号")

    except:

        return jsonify(code=-103, msg="请先验证旧手机号")

    user = User.query.filter(User.phone==phone).first()
    if user:
        return jsonify(code=-1, msg="手机号已被绑定，请换个手机号～")



    try:
        uid.phone = phone
        db.session.commit()
        session.pop('update_phone_token')
        return jsonify(code=0, msg="手机号换绑成功～")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="手机号换绑失败～")






def recursion_usr():
    uln = '0123456789'
    rs = random.sample(uln, 10)  # 生成一个 指定位数的随机字符串
    username = str(random.randint(1, 9)) + "".join(rs)
    user = User.query.filter(User.username == username).first()
    if not user:
        return username

    recursion_usr()


def getCodeInfo(list):
    data = []
    # 遍历列表
    for i in list:
        data.append({
            "x": random.randint(i["x1"], i["x2"]),
            "y": random.randint(i["y1"], i["y2"])
        })
    # 加密后的base64位数据
    data = base64.b64encode(json.dumps(data).encode('utf-8'))
    # 解密后的数据
    # print(json.loads(base64.b64decode(data)))
    aes = AesCrypto(AESKEY)
    encrypted = aes.encrypt(data)


def recursion_cookies():
    cookie = str(uuid.uuid4())
    cookie_obj = User_Cookies.query.filter(User_Cookies.cookies == cookie).first()
    if not cookie_obj:
        return cookie

    recursion_cookies()
